package gwtool.gui.login;

import gwtool.container.Benutzter;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.concurrent.Semaphore;

import javax.swing.JFrame;

public class LoginController implements ActionListener {

	private JFrame frame;

	private LoginPanel panel;

	private Semaphore loginSema = new Semaphore(0);

	public LoginController(String version) {

		frame = new JFrame();
		panel = new LoginPanel(this);
		frame.add(panel);
		frame.setTitle("GW-Tool " + version);
		frame.setSize(300, 150);
		frame.setLocationRelativeTo(null);
		frame.setVisible(true);
		addWindowAdapter();
	}

	@Override
	public void actionPerformed(ActionEvent e) {

		if (e.getSource() == panel.getBtnLogin() || e.getSource() == panel.getPasswordField()) {
			loginSema.release();
		}
		if (e.getSource() == panel.getBtnSchliessen()) {
			System.exit(0);
		}
	}

	public Benutzter getBenutzter() {

		try {
			loginSema.acquire();
		} catch (InterruptedException e) {
		}
		Benutzter benutzter = new Benutzter();
		benutzter.setEMail(panel.getEmailTextField().getText());
		benutzter.setPwHash(new String(panel.getPasswordField().getPassword()));
		frame.dispose();
		return benutzter;
	}

	private void addWindowAdapter() {

		frame.addWindowListener(new WindowAdapter() {

			@Override
			public void windowClosing(WindowEvent e) {

				System.exit(0);
			}

			@Override
			public void windowClosed(WindowEvent e) {

			}
		});
	}
}
